<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyId">
        <treeselect v-model="queryParams.companyId" :options="deptOptions" placeholder="请选择公司" :show-count="true" style="width: 160px"  clearable/> 
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceId" >
        <el-select v-model="queryParams.deviceId" placeholder="设备名称" style="width: 160px"  clearable>
          <el-option v-for="device in deviceOptions" :key="device.id" :label="device.name"
          :value="device.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="实验日期">
        <el-date-picker
          v-model="daterangeExperimentTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="上传时间">
        <el-date-picker
          v-model="daterangeUploadTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="上传人" prop="uploadUserName">
        <el-input
          v-model="queryParams.uploadUserName"
          placeholder="请输入上传人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实验报告文件名" prop="experimentFileName">
        <el-input
          v-model="queryParams.experimentFileName"
          placeholder="请输入实验报告文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oil:experiment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oil:experiment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oil:experiment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oil:experiment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="experimentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <!-- <el-table-column label="公司id" align="center" prop="companyId" /> -->
      <el-table-column label="公司名称" align="center" prop="companyName" />
      <!-- <el-table-column label="设备id" align="center" prop="deviceId" /> -->
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="实验日期" align="center" prop="experimentTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.experimentTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="上传人" align="center" prop="uploadUserId" /> -->
      <el-table-column label="上传人" align="center" prop="uploadUserName" />
      <el-table-column label="实验报告文件名" align="center" prop="experimentFileName" >
      <!-- <el-table-column label="实验报告文件路径" align="center" prop="experimentFilePath" /> 
      <template slot-scope="scope">
            <a :href="scope.row.experimentFilePath" download="scope.row.experimentFileName" target="_blank">{{ scope.row.experimentFileName }}</a >
          </template>
        </el-table-column> -->
        <template slot-scope="scope">
          <a :href="scope.row.filePath" target="_blank" class="buttonText">{{scope.row.experimentFileName}}</a>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['oil:experiment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            title="附件下载"
            icon="el-icon-download"
            @click="downloadExperiment(scope.row)"
            v-hasPermi="['oil:experiment:download']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['oil:experiment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改oilExperimentExport对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公司名称" prop="companyId">
          <!-- <el-input v-model="form.companyId" placeholder="请输入公司名称" /> -->
           <treeselect v-model="form.companyId" :options="deptOptions" placeholder="请选择公司名称" :show-count="true"/> 
        </el-form-item>
        <!-- <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" />
        </el-form-item> -->
        <el-form-item label="设备名称" prop="deviceName">
          <el-select v-model="form.deviceId" placeholder="设备名称">
            <el-option v-for="device in deviceOptions" :key="device.id" :label="device.name"
            :value="parseInt(device.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="实验日期" prop="experimentTime">
          <el-date-picker clearable
            v-model="form.experimentTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择实验日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实验报告文件名" prop="experimentFileName">
          <el-input v-model="form.experimentFileName" placeholder="请输入实验报告文件名" :disabled="true"/>
        </el-form-item>
        <!-- <el-upload
          ref="upload"
          class="upload-demo"
          :http-request="uploadBookFile1"
          :before-upload="beforeUpload"
          :file-list="fileList"
          :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传一个 pdf 文件，且不超过 300MB</div> -->
        <el-form-item label="上传文件" >
          <el-upload
            ref="upload"
            class="upload-demo"
            :http-request="uploadBookFile1"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="1" 
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <!-- <el-button type="primary" @click="submitForm2">上传文件</el-button> -->
          </el-upload>
        </el-form-item> 
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExperiment, getExperiment, delExperiment, addExperiment, updateExperiment,uploadBookFile } from "@/api/oil/experiment";
import { listDevice } from "@/api/oil/device";
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Experiment",
  // dicts: [ 'oil_industry_type'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // oilExperimentExport表格数据
      experimentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 实验报告文件路径时间范围
      daterangeExperimentTime: [],
      // 实验报告文件路径时间范围
      daterangeUploadTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        companyName: null,
        deviceId: null,
        deviceName: null,
        experimentTime: null,
        uploadTime: null,
        uploadUserId: null,
        uploadUserName: null,
        experimentFileName: null,
        experimentFilePath: null
      },
      upload: {
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyId: [
          { required: true, message: "公司id不能为空", trigger: "blur" }
        ],
        // companyName: [
        //   { required: true, message: "公司名称不能为空", trigger: "blur" }
        // ],
        deviceId: [
          { required: true, message: "设备id不能为空", trigger: "change" }
        ],
        // deviceName: [
        //   { required: true, message: "设备名称不能为空", trigger: "blur" }
        // ],
        experimentTime: [
          { required: true, message: "实验日期不能为空", trigger: "blur" }
        ],
        // experimentFileName: [
        //   { required: true, message: "实验报告文件名不能为空", trigger: "blur" }
        // ],
      },
      //设备名称
      deviceOptions:[],
      // 部门树选项
      deptOptions: undefined,
      fileList: []// 上传的文件列表
    };
  },
  created() {
    this.getList();
    this.getDevices();
    this.getDeptTree();
  },
  methods: {
    /** 查询oilExperimentExport列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeExperimentTime && '' != this.daterangeExperimentTime) {
        this.queryParams.params["beginExperimentTime"] = this.daterangeExperimentTime[0];
        this.queryParams.params["endExperimentTime"] = this.daterangeExperimentTime[1];
      }
      if (null != this.daterangeUploadTime && '' != this.daterangeUploadTime) {
        this.queryParams.params["beginUploadTime"] = this.daterangeUploadTime[0];
        this.queryParams.params["endUploadTime"] = this.daterangeUploadTime[1];
      }
      listExperiment(this.queryParams).then(response => {
        this.experimentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyId: null,
        companyName: null,
        deviceId: null,
        deviceName: null,
        experimentTime: null,
        uploadTime: null,
        uploadUserId: null,
        uploadUserName: null,
        experimentFileName: null,
        experimentFilePath: null,
        fileList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeExperimentTime = [];
      this.daterangeUploadTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实验报告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExperiment(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改实验报告";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.upload.submit();
      this.$refs.upload.clearFiles(); 
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除相关的数据项？').then(function() {
        return delExperiment(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    downloadExperiment(row) {
      const fileUrl = "http://"+location.host + row.experimentFilePath;
      
      // 使用 window.open 在新标签页打开下载链接 以 / 开头：表示相对于域名的根路径，会自动添加当前主机的 IP 和端口。
  const newWindow = window.open(fileUrl, '_blank');
  
  // 如果新窗口没有打开，可以提示用户检查浏览器的弹窗拦截器设置
  if (!newWindow) {
    this.$message.error("请检查浏览器的弹窗拦截设置");
  }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oil/experiment/export', {
        ...this.queryParams
      }, `experiment_${new Date().getTime()}.xlsx`)
    },
    getDevices(){
      listDevice({pageSize:5000}).then(res=>{
        this.deviceOptions = res.rows;
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    handleRemove(file, fileList) {
      console.log('删除文件:', file, fileList);
    },
    uploadFileFun(file){
      var test = /(doc|docx|pdf|txt)$/.test(file.name.split('.').pop().toLowerCase());
      if (!test) {
        this.$message.error("请上传正确的文档格式!");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 20MB!");
        return false;
      }
    },
    uploadBookFile1(file){
      let formData = new window.FormData();
      formData.append("file", file.file);

      // 发送上传请求
      uploadBookFile(formData).then((res) => {
        this.form.experimentFileName = res.newFileName;
        this.form.experimentFilePath = res.filePath;
        this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExperiment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExperiment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
      }).catch((error) => {
        console.error("文件上传失败:", error);
        this.$message.error("文件上传失败");
      });
      }
  }
};
</script>
